﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using QuanLyNganHangDe.BLL;
using QuanLyNganHangDe.DAL;
using QuanLyNganHangDe.DAL.Models;
using System.Threading;

namespace QuanLyNganHangDe.GUI.DuLieu
{

    /// <summary>
    /// Form ngân hàng câu hỏi
    /// </summary>
    public partial class FormNganHangCauHoi_Import : Form
    {
        public FormNganHangCauHoi_Import(DonViPhuTrach donvi, HocPhan hocphan)
        {
            InitializeComponent();
            NapDanhSachDonVi();
            cbxKhoa_BoMon.SelectedValue = donvi.MaDonVi;
            NapDanhSachHocPhan();
            cbxHocPhan.SelectedValue = hocphan.MaHocPhan;

            gridCauHoi.AllowUserToAddRows = false;
            gridCauHoi.AllowUserToDeleteRows = false;
            gridCauHoi.ReadOnly = true;
            gridCauHoi.AutoGenerateColumns = false;
            gridCauHoi.ColumnIndexToGroup = "0;3";
            colPhan_Phan.DataPropertyName = "MaKhoi";
            colPhan_STTCauHoi.DataPropertyName = "TenCauHoi";
            colPhan_NoiDung.DataPropertyName = "NoiDungCauHoi_Unicode";
            colPhan_Diem.DataPropertyName = "MaCauHoi";
        }
        void NapDanhSachDonVi()
        {
            bsKhoa_BoMon.DataSource = BizDonViPhuTrach.GetListDonViPhuTrach();
            cbxKhoa_BoMon.DataSource = bsKhoa_BoMon;
            cbxKhoa_BoMon.DisplayMember = "TenDonVi";
            cbxKhoa_BoMon.ValueMember = "MaDonVi";

        }

        void NapDanhSachHocPhan()
        {
            var donVi = bsKhoa_BoMon.Current as DonViPhuTrach;
            if (donVi != null)
            {
                bsHocPhan.DataSource = BizHocPhan.GetListHocPhanForCbx(donVi);
                cbxHocPhan.DataSource = bsHocPhan;
                cbxHocPhan.DisplayMember = "TenHocPhan";
                cbxHocPhan.ValueMember = "MaHocPhan";
            }
        }

        #region private string FileName;
        private string m_FileName;
        private string FileName
        {
            get { return m_FileName; }
            set
            {
                m_FileName = value;
                txtFileName.Text = m_FileName;
            }
        }

        List<CauHoi> dsCauHoi;
        #endregion

        private void lnkSelectFile_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Tập tin Word (*.docx)|*.docx|Tất cả (*.*)|*.*";
            if (dlg.ShowDialog() == DialogResult.OK)
                this.FileName = dlg.FileName;
        }

        private void btnDocDuLieu_Clicked(object sender, EventArgs e)
        {
            KillAllWordProcess();
            rtbCauHoi.Text = "";
            rtbDapAn.Text = "";
            bsPhan.DataSource = null;
            var progress = new FormProgress();
            bool coSuDungDapAn = chkHaveAnswer.Checked;
            progress.DoWork += (oSender, oE) =>
            {
                WordHelper wH = new WordHelper();
                string fileName = txtFileName.Text;
                var fi = new System.IO.FileInfo(fileName);
                #region Dung commented
                /*
            #region 1. createFolder("%AppData%/QLNHD");
            string folderPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                    "QLNHD");
            if (System.IO.Directory.Exists(folderPath) == false)
            {
                try
                {
                    System.IO.Directory.CreateDirectory(folderPath);
                }
                catch (Exception exc)
                {
                    DialogUtils.ShowError("Không thể tạo thư mục tạm cho chương trình được.\nChi tiết lỗi: " + exc.Message);
                    return;
                }
            }
            #endregion

            #region 2. string taggedFileName = ...
            string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fileName);
            int idx = 0;
            string taggedFileName;
            while (true)
            {
                if (idx == 0)
                    taggedFileName = System.IO.Path.Combine(folderPath, string.Format("{0}.docx", fileNameWithoutExtension));
                else
                    taggedFileName = System.IO.Path.Combine(folderPath, string.Format("{0}-{1}.docx", fileNameWithoutExtension, idx));

                bool taggedFileNameIsOK = false;
                if (System.IO.File.Exists(taggedFileName))
                {
                    #region Xem thử có thể xoá được file này hay không
                    try
                    {
                        System.IO.File.Delete(taggedFileName);
                        taggedFileNameIsOK = true;
                    }
                    catch
                    {
                        taggedFileNameIsOK = false;
                    }
                    #endregion
                }
                else
                    taggedFileNameIsOK = true;

                if (taggedFileNameIsOK == false)
                    idx++;
                else
                    break;
            }
            #endregion

            #region 3. create taggedFileName from fileName
            try
            {
                QuanLyNganHangDe.BLL.WordConvertor.Utils.ExportTaggedDocumentOf(fileName, taggedFileName);
            }
            catch (Exception exc)
            {
                DialogUtils.ShowError(string.Format("Không thể tạo tệp đánh dấu cho tệp [{0}] được.\nChi tiết lỗi {1}", fileName, exc.Message));
            }
            #endregion
            */

                #endregion

                this.Invoke((MethodInvoker)delegate
                {
                    dsCauHoi = wH.ReadMSWordToListQuestion(fileName, coSuDungDapAn);
                });
            };
            progress.RunWorkerCompleted += (oSender, oE) =>
            {
                if (dsCauHoi != null && dsCauHoi.Count > 0)
                {
                    bsPhan.DataSource = dsCauHoi;
                    gridCauHoi.DataSource = bsPhan;
                    btnNapDuLieu.Enabled = true;
                }
                else
                {
                    bsPhan.DataSource = null;
                    gridCauHoi.DataSource = bsPhan;
                    btnNapDuLieu.Enabled = false;
                }
                KillAllWordProcess();
            };
            progress.StartWorking(this);
        }
        void KillAllWordProcess()
        {
            try
            {
                System.Diagnostics.Process[] aProcWrd = System.Diagnostics.Process.GetProcessesByName("WINWORD");
                foreach (var process in aProcWrd)
                    process.Kill();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error. Detail: " + ex.Message);
            }
        }

        private void gridSinhVien_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            #region Commented
            //foreach (DataGridViewRow row in gridPhan.Rows)
            //{
            //    if (row.DataBoundItem == null)
            //        return;
            //    var drow = row.DataBoundItem as DataRowView;
            //    if (drow == null)
            //        return;

            //    var cell = row.Cells[ColSinhVien_TrangThai.Index] as DataGridViewTextBoxCell;
            //    if (cell == null)
            //        return;
            //    object oTrangThai = row.Cells[ColSinhVien_TrangThai.Index].Value;
            //    if (oTrangThai != null && oTrangThai != DBNull.Value)
            //    {
            //        string trangThai = oTrangThai.ToString();
            //        if (trangThai.Equals(BizSinhVien.ImportStatus.IN_ERROR) ||
            //            trangThai.Equals(BizSinhVien.ImportStatus.IN_ERROR_NOT_ENOUGH))
            //        {
            //            cell.Style.SelectionForeColor = cell.Style.ForeColor = Color.Brown;
            //            //cell.Style.SelectionBackColor = cell.Style.BackColor = Color.LightPink;
            //        }
            //        else if (trangThai.Equals(BizSinhVien.ImportStatus.IN_OK))
            //        {
            //            cell.Style.SelectionForeColor = cell.Style.ForeColor = Color.Black;
            //            //cell.Style.SelectionBackColor = cell.Style.BackColor = Color.White;
            //        }
            //        else if (trangThai.Equals(BizSinhVien.ImportStatus.OUT_OK))
            //        {
            //            cell.Style.SelectionForeColor = cell.Style.ForeColor = Color.DarkGreen;
            //            //cell.Style.SelectionBackColor = cell.Style.BackColor = Color.White;
            //        }
            //        else if (trangThai.Equals(BizSinhVien.ImportStatus.OUT_ERROR_ALREADY_EXIST) ||
            //            trangThai.Equals(BizSinhVien.ImportStatus.OUT_ERROR_GENERAL))
            //        {
            //            cell.Style.SelectionForeColor = cell.Style.ForeColor = Color.Red;
            //            //cell.Style.SelectionBackColor = cell.Style.BackColor = Color.LightPink;
            //        }
            //        else
            //        {
            //            cell.Style = gridCauHoi.DefaultCellStyle;
            //        }
            //    }
            //} 
            #endregion
        }

        private void txtFileName_TextChanged(object sender, EventArgs e)
        {
            btnDocDuLieu.Enabled = true;
            btnNapDuLieu.Enabled = false;
            bsPhan.DataSource = null;
            gridCauHoi.DataSource = bsPhan;
            //rtfCauHoi.Rtf = "";
            //rtfDapAn.Rtf = "";
            rtbCauHoi.Text = "";
            rtbDapAn.Text = "";
        }

        private void bsPhan_CurrentChanged(object sender, EventArgs e)
        {
            var question = bsPhan.Current as CauHoi;
            if (question != null && dsCauHoi != null && dsCauHoi.Count > 0)
                for (int i = 0; i < dsCauHoi.Count; i++)
                {
                    var item = dsCauHoi[i];
                    if (gridCauHoi.SelectedRows != null && gridCauHoi.SelectedRows.Count > 0)
                        if (i == gridCauHoi.SelectedRows[0].Index)
                        {
                            //rtfCauHoi.Rtf = item.NoiDungCauHoi_RTF;
                            rtbCauHoi.Load(item.NoiDungCauHoi_RTF, TXTextControl.StringStreamType.RichTextFormat);
                            lbKhoi.Text = item.Khoi.TenKhoi;
                            lbCau.Text = item.TenCauHoi;
                            lbDiem.Text = "(" + item.Khoi.SoDiem + ")";
                            //rtfDapAn.Rtf = item.NoiDungTraLoi_RTF;
                            if (!string.IsNullOrEmpty(item.NoiDungTraLoi_RTF))
                                rtbDapAn.Load(item.NoiDungTraLoi_RTF, TXTextControl.StringStreamType.RichTextFormat);
                            break;
                        }
                }
        }

        private void btnXuatDuLieu_Click(object sender, EventArgs e)
        {
            //<<<<<<< .mine
            //DeInRa de = new DeInRa();
            //de.MaDeThi = Guid.NewGuid().ToString();
            //de.LanThi = 2;
            //de.GioThi = "17h50";
            //de.NgayThi = "01/08/2012";
            //de.ThoiGianLamBai = 90;
            //de.DuocSuDungTaiLieu = false;
            //de.HocKy = new HocKy();
            //de.HocKy.NamHoc = new NamHoc();
            //de.HocKy.TenHocKy = 1;
            //de.HocKy.NamHoc.NamHoc1 = "2012-2013";
            //HocPhan hp = BizHocPhan.GetHocPhan(cbxHocPhan.SelectedValue.ToString());
            ////Exam exam = new Exam() { Credits = 3, OrderExam = 1, IdExam = "KH_123", Semester = "HỌC KỲ 2, NĂM HỌC 2012 - 2013", SubjectId = "TIN1013", SubjectName = "TIN HỌC ĐẠI CƯƠNG", TimeExam = 120, TypeExamination = TypeExam.DontUseDocument };
            //new WordHelper().WriteListQuestionToWord(Application.StartupPath + "\\TEMPLATE\\MauDeThiVaDapAn.doc", hp, listQuestion, de);
            //=======
            DeInRa de = new DeInRa();
            de.MaDeThi = Guid.NewGuid().ToString();
            de.LanThi = 2;
            de.GioThi = "17h50";
            de.NgayThi = "01/08/2012";
            de.ThoiGianLamBai = 90;
            de.DuocSuDungTaiLieu = false;
            de.DotThi = new DotThi();
            de.DotThi.HocKy = new HocKy();
            de.DotThi.HocKy.NamHoc = new NamHoc();
            de.DotThi.HocKy.TenHocKy = 1;
            de.DotThi.HocKy.NamHoc.NamHoc1 = "2012-2013";
            HocPhan hp = BizHocPhan.GetHocPhan(cbxHocPhan.SelectedValue.ToString());
            //Exam exam = new Exam() { Credits = 3, OrderExam = 1, IdExam = "KH_123", Semester = "HỌC KỲ 2, NĂM HỌC 2012 - 2013", SubjectId = "TIN1013", SubjectName = "TIN HỌC ĐẠI CƯƠNG", TimeExam = 120, TypeExamination = TypeExam.DontUseDocument };
            new WordHelper().WriteListQuestionToWord(Application.StartupPath + "\\TEMPLATE\\MauDeThiVaDapAn.doc", hp, dsCauHoi, de);
            //>>>>>>> .r76
        }

        private void bsKhoa_BoMon_CurrentChanged(object sender, EventArgs e)
        {
            NapDanhSachHocPhan();
        }

        private void btnNapDuLieu_Click(object sender, EventArgs e)
        {
            HocPhan hp = null;
            string hpString = cbxHocPhan.SelectedValue.ToString();

            string iRet = "-1";
            var pr = new BackgroundWorker();
            pr.DoWork += (oSender, oE) =>
            {
                hp = BizHocPhan.GetHocPhan(hpString);
                if (hp != null)
                    iRet = BizCauHoi.AddDSCauHoi(dsCauHoi, hp);
            };
            pr.RunWorkerCompleted += (oSender, oE) =>
            {
                if (iRet != "-1")
                    MessageBox.Show("Danh sách câu hỏi đã lưu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                    MessageBox.Show("Lỗi: " + iRet, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                picBusy.Visible = false;
            };
            picBusy.Visible = true;
            pr.RunWorkerAsync();

        }
    }
}
